﻿using bleissem.CMWVS.Helpers;
using bleissem.CMWVS.UI;
using CMWVS.Core.Commands;
using CMWVS.Core.Mono;
using EnvDTE;
using EnvDTE80;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace bleissem.CMWVS.Commands
{
    public class RunCommand : BaseCommand
    {
        #region Constructor

        public RunCommand()
            : base(new CommandID(GuidList.GuidCMWVS_Plugin_Run, (int)PkgCmdIDList.IDCMWS_Plugin_Run))
        {
        }

        #endregion Constructor

        protected override void OnBeforeQueryStatus()
        {
            this.Enabled = base.Resolver.Get<MonoConfig>().IsInstalled;

            base.OnBeforeQueryStatus();
        }

        protected override bool CanExecute()
        {
            return IsSolutionLoaded.Execute(base.Resolver);
        }

        protected override void Execute()
        {
            var run = base.m_MainViewModel.Run;
            if (run.CanExecute())
            {
                ToOutputWindow outputWindow = new ToOutputWindow(base.Resolver);
                outputWindow.Clear();

                using (TraceListener traceListener = new AddInTraceListener((string message) =>
                {
                    outputWindow.OutPut(message);
                }))
                {
                    DTE2 dte2 = base.Resolver.Get<DTE2>();
                    EnvDTE.Solution solution = dte2.Solution;
                    IEnumerable<Project> projects = VisualStudioHelper.GetProjects(solution);

                    List<RunCommandParameters.Item> Items = new List<RunCommandParameters.Item>();

                    string startArgs = string.Empty;
                    string toRun = string.Empty;

                    foreach (Project project in projects)
                    {
                        startArgs = VisualStudioHelper.GetStartArguments(project);

                        toRun = VisualStudioHelper.GetToRun(project);

                        DirectoryInfo workingDir = VisualStudioHelper.ProjectFolderDir(project);

                        Items.Add(new RunCommandParameters.Item(toRun, startArgs, workingDir));
                    }

                    RunCommandParameters runParams = new RunCommandParameters(Items);

                    run.Execute(runParams);
                    var result = run.Result;
                }
            }
        }
    }
}